<template>
    <div class="Chat" @contextmenu="contextmenu">
        <div class="Menu" ref="Menu">
            <div>
                <button data-text @click="DeleteChat">删除</button>
            </div>
            <div> <button data-text :disabled="DisabledFlag" @click="CancelTexy">撤销</button></div>
        </div>
        <div v-if="FlagNum == 200">
            <div class="ChatBox">
                <div class="ChatBoxHead">
                    {{ FlagName }}<button data-text @click="Back">返回</button>
                </div>
                <div class="ChatBoxConter">
                    <div class="ChatBoxConterBox" v-if="ListChat.length > 0" ref="ChatBoxConterBox">
                        <div v-for="item in ListChat" :key="item.chatId" class="ChatBoxConterBoxFor">
                            <div v-if="item.chatMailbox == Uid" class="ChatBoxConterBoxForLeft ChatBoxConterBoxForTotal">
                                <div class="ChatBoxConterBoxForLeftTitle">
                                    <span @contextmenu="contextmenuText($event, 1, item)" v-if="item.chatType == 'Text'">{{
                                        item.chatText
                                    }}</span>
                                    <img :src="item.chatText" alt="" v-else-if="item.chatType == 'Photo'"
                                        @click="PhotoBig(item.chatText)" @contextmenu="contextmenuText($event, 1, item)">
                                </div>
                            </div>
                            <div v-else class="ChatBoxConterBoxForRight ChatBoxConterBoxForTotal">
                                <div class="ChatBoxConterBoxForLeftTitle">
                                    <span @contextmenu="contextmenuText($event, 2, item)" v-if="item.chatType == 'Text'">{{
                                        item.chatText
                                    }}</span>
                                    <img :src="item.chatText" alt="" v-else-if="item.chatType == 'Photo'"
                                        @click="PhotoBig(item.chatText)" @contextmenu="contextmenuText($event, 2, item)">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="ChatBoxConterBox" v-else>
                        <Zky_Error :title="'暂无聊天记录'"></Zky_Error>
                    </div>
                </div>
                <div class="ChatBoxFooter">
                    <div style="height:100%">
                        <textarea @keydown="KeyDown" @change="ChangeText" v-model="MessageList.chatText"
                            v-if="MessageList.chatType == 'Text'"></textarea>
                    </div>
                    <div class="ChatBoxFooterBox">

                        <div class="Img" v-if="MessageList.chatType == 'Photo'">
                            <div class="ImgBox">
                                <img :src="MessageList.chatText" alt="">
                            </div>
                            <div class="ImgSpan">
                                <span @click="DeletePhoto">删除</span>
                                <span @click="SeePhoto">查看大图</span>
                            </div>
                        </div>

                    </div>
                    <div>
                        <button @click="ChatMessage" style="margin-right:0;">发送</button>
                        <button @click="Voice">语音输入</button>
                    </div>
                    <div>
                        <label for="file" class="labelFile">上传图片</label>
                        <input type="file" @change="FileChage" id="file" ref="file">
                    </div>
                </div>
            </div>
        </div>
        <div v-else-if="FlagNum == 201">
            <Zky_Error :title="FlagMessage"></Zky_Error>
        </div>
        <div class="SeePhototBig" v-if="PhotoFlag" @dblclick="ClosePotho">
            <img :src="PhotoUrl" alt="">
        </div>
    </div>
</template>

<script setup lang="ts">
import Axios from '../../Axios/Axios';
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted, watch } from 'vue';
import { main } from '../../store';
import { message } from 'ant-design-vue';
// import { Time } from '../../utils/Time';
const Mains = main()
Mains.Home = 1
Mains.Buddy = 2
const route = useRoute()
const router = useRouter()
const FlagNum = ref(0)
const file = ref()
const ChatBoxConterBox = ref()
const Menu = ref()
const Uid = route.query.id
const PhotoUrl = ref("")
const PhotoFlag = ref(false)
const DisabledFlag = ref(false)
const FlagMessage = ref("")
const FlagName = ref("")
const ListChat = ref([{
    chatId: "",
    chatMailbox: "",
    chatText: "",
    chatType: ""
}])
const MessageList = ref({
    chatMailBoxOthers: route.query.id,
    chatText: "",
    chatType: "Text",
})
const ChatListMessage = ref({
    chatMailBoxOthers: "",
    chatText: "",
    chatType: "Text",
    chatMailbox: ""
})
onMounted(async () => {
    await init()
    await ChatInit()
    await ChatTypeList()
    setTimeout(() => { Scroll() }, 100)
})

watch(() => Mains.WebSocketMessageFlag, async () => {
    await ChatInit()
    setTimeout(() => { Scroll() }, 100)
})

// 返回
const Back = () => {
    router.go(-1)
}

// 撤销消息
const CancelTexy = async () => {
    ChatListMessage.value.chatMailbox = "cancel"
    const res = await Axios("ChatDelete", ChatListMessage.value)
    ChatListMessage.value.chatType = "Delete"
    await Mains.webSocket.send(JSON.stringify(ChatListMessage.value))
    if (res.code == 200) {
        await ChatInit()
        DisabledFlag.value = false
        Scroll()
        Menu.value.style.display = "none"
        message.success(res.message)
    } else {
        message.warning(res.message)
    }
}

// 删除聊天信息
const DeleteChat = async () => {

    ChatListMessage.value.chatMailbox = "delete"
    const res = await Axios("ChatUpdateMailboxType", ChatListMessage.value)
    if (res.code == 200) {
        await ChatInit()

        DisabledFlag.value = false
        Scroll()
        Menu.value.style.display = "none"
        message.success(res.message)
    } else {
        message.warning(res.message)
    }
}

// 查看聊天图片大图
const PhotoBig = (url: string) => {
    PhotoUrl.value = url
    PhotoFlag.value = true
}

// 消息右击菜单事件
const contextmenuText = (e: any, num: number, obj: any) => {
    setTimeout(() => {
        Menu.value.style.display = "inline-block"
        Menu.value.style.top = e.y + "px"
        Menu.value.style.left = e.x + "px"
        ChatListMessage.value = JSON.parse(JSON.stringify(obj))

        // 如果num==1对方发送的消息
        if (num == 1) {
            DisabledFlag.value = true
        } else if (num == 2) {
            if (new Date(obj.chatTime).getTime() + 1000 * 60 * 10 < new Date().getTime()) {
                DisabledFlag.value = true
            }
        }
        // 如果num==2 我方发送的消息
    }, 0)

}
// 关闭全局右击菜单事件
const contextmenu = (e: any) => {
    e.preventDefault()
    Menu.value.style.display = "none"
    DisabledFlag.value = false
}

const Scroll = () => {
    if (ListChat.value.length > 0) {
        // 初始化聊天消息位置
        if (ChatBoxConterBox.value) {
            ChatBoxConterBox.value.scrollTop = ChatBoxConterBox.value.scrollHeight
        }
    }
}


// 双击关闭查看大图
const ClosePotho = () => {
    PhotoFlag.value = false
    PhotoUrl.value = ""
}

// 查看大图
const SeePhoto = () => {
    PhotoUrl.value = MessageList.value.chatText
    PhotoFlag.value = true
}

// 删除照片
const DeletePhoto = () => {
    MessageList.value.chatText = ""
    MessageList.value.chatType = "Text"
    file.value.value = ""
}

// 语言输入
const Voice = () => {
    const Recognition = new webkitSpeechRecognition()
    // Recognition.continuous = true;
    Recognition.lang = 'cmn-Hans-CN'
    Recognition.start()
    let one = <any>[]
    Recognition.onresult = (e: any) => {
        // console.log(e.results);
        one = e.results[0]

    }
    Recognition.onerror = () => {
        message.warning("没有识别到声音，或者您的浏览器不支持语言输入")

    }
    Recognition.onend = () => {
        if (MessageList.value.chatType == "Photo") {
            MessageList.value.chatType = "Text"
            MessageList.value.chatText = ""
        }

        if (one.length > 0) {
            for (let index = 0; index < one.length; index++) {
                MessageList.value.chatText += one[index].transcript

            }


        } else {
            MessageList.value.chatText = ""
        }
        message.warning("识别结束")
    }

}

// 选择图片之前
const FileChage = (e: any) => {
    let file = e.target.files[0]
    // 设置文件最大值
    let max = 1024 * 1024
    if (file.size > max) {

        // e.target.outerHTML = e.target.outerHTML
        e.target.value = ""
        message.warning("文件不能大于1MB")
        return
    }
    // 判断类型
    let one = ["jpg", "jpeg", "png"]
    if (file.type.toLowerCase().includes(one[0]) || file.type.toLowerCase().includes(one[1]) || file.type.toLowerCase().includes(one[2])) {
        // 将图片转换成bast64
        const f = new FileReader()
        console.log(f);
        f.onload = (e) => {
            MessageList.value.chatType = "Photo"
            MessageList.value.chatText = <string>e.target?.result


        }
        f.onerror = () => {
            e.target.outerHTML = e.target.outerHTML
            message.warning("图片上传失败")
        }


        f.readAsDataURL(file)
    } else {
        e.target.outerHTML = e.target.outerHTML
        message.warning("只支持png/jpg格式文件")
        return
    }
}

// 鼠标按下
const KeyDown = (e: any) => {
    if (e.code == "Enter" || e.keyCode == 13) {
        ChatMessage()
    }
}
// 输入框改变事件
const ChangeText = () => {
    MessageList.value.chatType = "Text"
}
// 发送消息
const ChatMessage = async () => {
    // console.log(1);
    // 发送文本消息
    if (MessageList.value.chatType == "Text") {
        if (MessageList.value.chatText != "") {
            Mains.webSocket.send(JSON.stringify(MessageList.value))
            setTimeout(async () => {
                await ChatInit()
                DeletePhoto()
                Scroll()
            }, 100)
        } else {
            message.warning("请输入内容之后发送")
        }
    } else if (MessageList.value.chatType == "Photo") {
        const ResImg = await Axios("ImageInformation", { imageBlob: MessageList.value.chatText })
        if (ResImg.code == 200) {
            // console.log(MessageList.value);
            MessageList.value.chatText = ResImg.data
            await Mains.webSocket.send(JSON.stringify(MessageList.value))
            setTimeout(async () => {
                await ChatInit()
                DeletePhoto()
                Scroll()
            }, 100)
        } else {
            message.warning("图片上传失败，无法发送消息")
        }
    }
}


// 更新聊天列表状态
const ChatTypeList = async () => {
    await Axios("ChatListUpdateNew", { chatListOthersMailbox: route.query.id })
}

// 初始化聊天信息
const ChatInit = async () => {
    ListChat.value = []
    const res = await Axios("ChatSelect", { chatMailBoxOthers: route.query.id })

    ListChat.value = res.data
    // ListChat.value = []
    // console.log(FlagNum.value == 200);
    // if (FlagNum.value == 200) {
    //     const res = await Axios("ChatSelect", { chatMailBoxOthers: route.query.id })
    //     console.log(res);
    //     ListChat.value = res.data
    // }
}
// 初始化用户信息
const init = async () => {
    const res = await Axios("SelectUserMailbox", { userMailbox: route.query.id })
    FlagNum.value = res.code
    FlagMessage.value = res.message
    FlagName.value = res.data.userNickname
}
</script>

<style scoped lang="scss">
$Text: #ffffff;

.Chat {
    width: 100%;
    height: 100%;

    .Menu {
        display: none;
        position: absolute;
        max-width: 400px;
        min-width: 60px;
        padding: 8px 10px;
        background: #646cff;
        left: 189px;
        top: 461px;
        border-radius: 10px;


        button {
            color: $Text !important;
        }

        button:hover {
            color: darken($color: $Text , $amount: 10%) !important;
        }

        button:active {
            color: darken($color: $Text , $amount: 20%) !important;
        }

        button:disabled {
            color: darken($color: $Text , $amount: 30%) !important;
        }
    }

    .SeePhototBig {
        cursor: pointer;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 3;
        background: rgba($color: #000000, $alpha: 0.2);

        img {
            display: block;
            width: 80%;
            height: 80%;
            margin: 0 auto;
            margin-top: 5%;
        }
    }

}

.ChatBox {
    width: 80vw;
    height: 80vh;
    background: #fff;
    margin: 0 auto;

    .ChatBoxHead {
        height: 8vh;
        border-bottom: 1px solid #bbb;
        line-height: 8vh;
        text-align: center;
        font-size: 1.6rem;

        button {
            padding: 0;
            font-size: 1rem;
        }
    }

    .ChatBoxConter {
        width: 100%;
        height: calc(100% - 16vh);
        overflow: hidden;
        padding: 20px 0px 20px 20px;

        .ChatBoxConterBox {
            width: calc(100% + 20px);
            height: 100%;
            overflow-y: scroll;
            padding-right: 20px;
            padding-right: 20px;

            .ChatBoxConterBoxFor {
                width: 100%;

                .ChatBoxConterBoxForTotal {

                    display: inline-block;
                    width: 70%;
                    margin-bottom: 10px;

                    .ChatBoxConterBoxForLeftTitle {
                        height: auto;

                        img {
                            height: auto;
                            width: 100%;
                            cursor: pointer;
                        }
                    }

                    span {
                        display: inline-block;
                        max-width: 100%;
                        background: red;
                        color: #fff;
                        padding: 8px 10px;
                        border-radius: 10px;
                        word-wrap: break-word;
                        text-align: left;
                    }
                }

                .ChatBoxConterBoxForLeft {
                    float: left;
                }

                .ChatBoxConterBoxForRight {
                    float: right;
                    text-align: right;

                    span {
                        background: #646cff;
                    }
                }
            }
        }
    }

    .ChatBoxFooter {
        height: 8vh;
        width: 100%;
        border-top: 1px solid #bbb;
        display: flex;
        align-items: center;
        justify-content: center;

        textarea {
            display: inline-block;
            resize: none;
            height: 70%;
            margin-top: 5%;
        }

        textarea:focus {
            outline: 1px solid #646cff;
        }

        button {
            padding: 6px 8px;
            border-radius: 10px;
            margin: 0 20px;
        }

        .ChatBoxFooterBox {
            height: 100%;

            .Img {
                display: inline-block;
                width: 140px;
                height: 100%;
                position: relative;

                .ImgSpan {
                    width: 100%;
                    /*display: flex;*/
                    display: none;
                    background: rgba($color: #ffffff, $alpha: .2);

                    justify-content: space-around;
                    position: absolute;
                    top: 1vh;
                    left: 0;
                    color: red;

                    span {
                        cursor: pointer;
                    }
                }

                .ImgBox {
                    width: 100%;
                    height: 100%;
                    line-height: 8vh;
                }

                img {
                    width: 100%;
                    height: 80%;
                    object-fit: cover;
                    cursor: pointer;
                }
            }

            .Img:hover .ImgSpan {
                display: flex;
            }

        }

        input[type="file"] {
            cursor: pointer;
            display: none;
        }

        .labelFile {
            display: inline-block;
            /*height: 40px;*/
            background: #646cff;
            /*line-height: 40px;*/
            color: #fff;
            padding: 6px 8px;
            border-radius: 10px;
            cursor: pointer;
        }
    }
}
</style>